import { createStore } from 'redux'

// 实现数据持久化
let userInfo = localStorage.getItem('userInfo')
try {
    userInfo = JSON.parse(userInfo) || {}
} catch (err) {
    userInfo = {}
}
let cartlist = localStorage.getItem('cartlist')
try {
    cartlist = JSON.parse(cartlist) || {}
} catch (err) {
    cartlist = {}
}

const initState = {
    userInfo,
    cartlist,
    common:{}
}

const reducer = (state,{type,payload})=>{
    let newState = {...state}
    switch(type){
        // {type:'login',payload:{...}}
        case 'login':
            newState.userInfo = payload
            localStorage.setItem('userInfo',JSON.stringify(payload))
            return newState;
        case 'logout':
            newState.userInfo = {}
            localStorage.removeItem('userInfo')
            return newState;

        case 'add':
            newState.cartlist = [payload,...state.cartlist]
            localStorage.setItem('cartlist',JSON.stringify(newState.cartlist))
            return newState;
        case 'remove':
            newState.cartlist = state.cartlist.filter(item=>item._id!==payload._id)
            localStorage.setItem('cartlist',JSON.stringify(newState.cartlist))
            return newState;
        case 'clear':
            newState.cartlist = []
            localStorage.removeItem('cartlist')
            return newState;
        case 'changeqty':
            newState.cartlist = state.cartlist.map(item=>{
                if(item._id === payload._id){
                    item.qty = payload.qty
                }
                return {...item}
            })
            localStorage.setItem('cartlist',JSON.stringify(newState.cartlist))
            return newState;
        default:
            return newState
    }
}

// 创建全局store仓库
const store = createStore(reducer,initState)

export default store;

// console.log('store',store);
// console.log('state',store.getState());


// store.subscribe(function(){
//     console.log('subscribe',store.getState())           
// })